package cn.kgc.easybuy.service.impl;

import cn.kgc.easybuy.dao.ProductESRepository;
import cn.kgc.easybuy.dao.ProductMapper;
import cn.kgc.easybuy.pojo.Product;
import cn.kgc.easybuy.service.ProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    private final  static Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);

    @Autowired
    private ProductESRepository productESRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public boolean delProduct(int id) {
        int flag = productMapper.delProduct(id);
        if (flag == 1){
            logger.info("删除商品:"+id+"成功");
            // 更新ES中商品数据
            saveAllProductToEs();
            return true;
        }else {
            throw new RuntimeException("删除商品"+id+"失败");
        }
    }

    @Override
    public boolean updateProduct(Product product) {
        int flag = productMapper.updateProduct(product);
        if (flag == 1){
            logger.info("修改商品:"+product.getName()+"成功");
            // 更新ES中商品数据
            saveAllProductToEs();
            return true;
        }else{
            logger.error("修改商品:"+product.getName()+"失败");
            throw new RuntimeException("修改商品:"+product.getName()+"失败");
        }
    }

    @Override
    public boolean addProduct(Product product) {
        int flag = productMapper.addProduct(product);
        if (flag == 1){
            logger.info("添加商品:"+product.getName()+"成功");
            // 更新ES中商品数据
            saveAllProductToEs();
            return true;
        }else {
            logger.error("添加商品" + product.getName() + "失败");
            throw new RuntimeException("添加商品" + product.getName() + "失败");
        }
    }

    @Override
    public Product selectProductById(int id) {
        Product product=productMapper.selectProductById(id);
        if (product != null){
            logger.info("查询商品"+id+"成功");
            return product;
        }else {
            logger.error("查询商品"+id+"失败");
            throw new RuntimeException("查询商品"+id+"失败");
        }
    }

    @Override
    public List<Product> selectProductAll() {
        logger.info("数据库查询商品开始");
        List<Product> list = productMapper.selectProductAll();
        return list;
    }

    public PageInfo<Product> selectProductByPageWithEs(Map<String,Object> params){
        String name=(String) params.get("name");
        Integer pageNum = Integer.parseInt(params.get("pageNum").toString())-1;
        Integer pageSize = Integer.parseInt(params.get("pageSize").toString());
        String createTime = (String) params.get("createTime");
        Integer categoryLevel1Id = 0;
        Integer categoryLevel2Id = 0;
        Integer categoryLevel3Id = 0;

        if (params.get("categoryLevel1Id") != null && StringUtils.isNotEmpty(params.get("categoryLevel1Id").toString())){
            categoryLevel1Id = Integer.parseInt(params.get("categoryLevel1Id").toString());
            logger.info("添加categoryLevel1Id过滤条件: " + categoryLevel1Id);
        }

        if (params.get("categoryLevel2Id") != null && StringUtils.isNotEmpty(params.get("categoryLevel2Id").toString())){
            categoryLevel2Id = Integer.parseInt(params.get("categoryLevel2Id").toString());
            logger.info("添加categoryLevel2Id过滤条件: " + categoryLevel2Id);
        }

        if (params.get("categoryLevel3Id") != null && StringUtils.isNotEmpty(params.get("categoryLevel3Id").toString())){
            categoryLevel3Id = Integer.parseInt(params.get("categoryLevel3Id").toString());
            logger.info("添加categoryLevel3Id过滤条件: " + categoryLevel3Id);
        }

        String priceSort = " ";
        if (params.get("priceSort") != null && StringUtils.isNotEmpty(params.get("priceSort").toString())){
            priceSort=params.get("priceSort").toString();
        }

        String salesSort =" ";
        if (params.get("salesSort") != null && StringUtils.isNotEmpty(params.get("salesSort").toString())){
            salesSort=params.get("salesSort").toString();
        }

        NativeSearchQueryBuilder queryBuilder=new NativeSearchQueryBuilder();
        // 构建查询条件
        if (name != null && !name.equals("")){
            queryBuilder.withQuery(QueryBuilders.matchQuery("name",name));
            logger.info("查询"+name+"数据");
        } else {
            queryBuilder.withQuery(QueryBuilders.matchAllQuery());
        }

        // 使用bool查询来组合多个过滤条件，避免覆盖问题
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        // 添加商品分类过滤条件
        if (categoryLevel1Id != 0){
            boolQueryBuilder.filter(QueryBuilders.termQuery("categoryLevel1Id",categoryLevel1Id));
        }
        if (categoryLevel2Id != 0){
            boolQueryBuilder.filter(QueryBuilders.termQuery("categoryLevel2Id",categoryLevel2Id));
        }
        if (categoryLevel3Id != 0){
            boolQueryBuilder.filter(QueryBuilders.termQuery("categoryLevel3Id",categoryLevel3Id));
        }

        // 添加年份过滤条件
        if (createTime != null && !createTime.equals("")) {
            // 将年份转换为日期范围
            String startDate = createTime + "-01-01";
            String endDate = createTime + "-12-31";

            boolQueryBuilder.filter(QueryBuilders.rangeQuery("createTime")
                    .gte(startDate)
                    .lte(endDate)
                    .format("yyyy-MM-dd"));
            logger.info("查询"+createTime+"年数据");
        }

        // 添加isDelete=0过滤条件，确保只查询未删除的商品
        boolQueryBuilder.filter(QueryBuilders.termQuery("isDelete", 0));

        queryBuilder.withFilter(boolQueryBuilder);

        //排序(价格降序[false]，销量降序[false])
        if (salesSort.equals("true")){
            queryBuilder.withSorts(SortBuilders.fieldSort("sales").order(SortOrder.ASC));
            logger.info("销量升序");
        }else if (salesSort.equals("false")){
            queryBuilder.withSorts(SortBuilders.fieldSort("sales").order(SortOrder.DESC));
            logger.info("销量降序");
        }else if (priceSort.equals("true")){
            queryBuilder.withSorts(SortBuilders.fieldSort("price").order(SortOrder.ASC));
            logger.info("价格升序");
        }else if (priceSort.equals("false")){
            queryBuilder.withSorts(SortBuilders.fieldSort("price").order(SortOrder.DESC));
            logger.info("价格降序");
        }else {
            queryBuilder.withSorts(SortBuilders.fieldSort("createTime").order(SortOrder.DESC));
            logger.info("默认时间降序");
        }

        //分页
        queryBuilder.withPageable(PageRequest.of(pageNum,pageSize));

        //设置高亮
        HighlightBuilder highlightBuilder=new HighlightBuilder();
        highlightBuilder.field("name")
                .preTags("<span style='color:red'>")
                .postTags("</span>");
        queryBuilder.withHighlightBuilder(highlightBuilder);

        //搜索命中
        NativeSearchQuery query = queryBuilder.build();
        SearchHits<Product> searchHits = elasticsearchRestTemplate.search(query, Product.class);
        List<Product> list = new ArrayList<>();
        for (SearchHit<Product> searchHit:searchHits){
            Product product = searchHit.getContent();
            Map<String,List<String>> map=searchHit.getHighlightFields();
            if (map != null && map.containsKey("name") && map.get("name") != null && !map.get("name").isEmpty()) {
                product.setName(map.get("name").get(0));
            }
            list.add(product);
        }

        //设置返回pageInfo
        PageInfo<Product> pageInfo = new PageInfo<>(list);
        pageInfo.setPageNum(pageNum+1);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotal((int)searchHits.getTotalHits());
        pageInfo.setPages((int)Math.ceil(pageInfo.getTotal()/pageInfo.getPageSize())+1);
        pageInfo.setList(list);
        pageInfo.setNextPage(pageInfo.getPageNum()+1<=pageInfo.getPages()?pageInfo.getPageNum()+1:0);
        pageInfo.setPrePage(pageInfo.getPageNum()-1>=1?pageInfo.getPageNum()-1:0);
        return pageInfo;
    }

    @Override
    public void saveAllProductToEs() {
        logger.info("ES保存商品数据");
        List<Product> list = selectProductAll();
        productESRepository.saveAll(list);
    }

    @Override
    public boolean sellProduct(Product product) {
        return productMapper.sellProduct(product)==1;
    }

    @Override
    public boolean refundProduct(Product product) {
        return productMapper.sellProduct(product)==1;
    }

}
